/**
 * 
 */
package be.jaisy.osgi.console.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;

import be.jaisy.osgi.console.service.api.IOsgiServiceManagementService;
import be.jaisy.osgi.console.service.api.to.OsgiServiceTo;
import be.jaisy.osgi.console.service.internal.Activator;
import be.jaisy.osgi.console.service.util.ConsoleHelper;
import be.jaisy.osgi.exception.OSGIRuntimeException;

/**
 * @author Stany Blanvalet
 * 
 */
public class OsgiServiceManagementServiceImpl implements IOsgiServiceManagementService {

	private BundleContext context;

	protected void activate(ComponentContext cc) {
		this.context = cc.getBundleContext();
	}

	protected void deactivate(ComponentContext context) throws Exception {
		this.context = null;
	}

	public Collection listRegisteredServices() {
		if (context == null)
			throw new IllegalStateException("Service not initialized with ComponentContext");
		List<OsgiServiceTo> result = new ArrayList<OsgiServiceTo>();
		try {
			for (ServiceReference serviceReference : context.getAllServiceReferences(null, null)) {
				result.add(ConsoleHelper.convert(serviceReference));
			}
		} catch (InvalidSyntaxException e) {
			Activator.logWarning(this.getClass(), "listRegisteredServices() failed", e);
			throw new OSGIRuntimeException(e);
		}

		Collections.sort(result, new Comparator<OsgiServiceTo>() {

			public int compare(OsgiServiceTo osgiServiceTo1, OsgiServiceTo osgiServiceTo2) {
				if (osgiServiceTo1.getDescription() == null)
					return -1;
				return osgiServiceTo1.getRegisteredBundleid().compareTo(osgiServiceTo1.getRegisteredBundleid());
			}
		});

		return result;
	}

	private static String SERVICE_KEY_ID = Constants.SERVICE_ID; 
	
	public OsgiServiceTo getRegisteredService(Long id) {
		if (context == null)
			throw new IllegalStateException("Service not initialized with ComponentContext");		
		try {
			for (ServiceReference serviceReference : context.getAllServiceReferences(null, null)) {
				if(id.equals(serviceReference.getProperty(SERVICE_KEY_ID)))
					return ConsoleHelper.convert(serviceReference);
			}
		} catch (InvalidSyntaxException e) {
			Activator.logWarning(this.getClass(), "listRegisteredServices() failed", e);
			throw new OSGIRuntimeException(e);
		}
		throw new IllegalArgumentException("Service id ["+id+"] not currently registered");		
	}



}
